<template>
  <div class="page-container product-permission-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-header__content">
        <h1 class="page-title">产品权限管理</h1>
        <p class="page-description">管理用户对产品的访问权限</p>
      </div>
      <div class="page-header__actions">
        <el-button
          type="primary"
          :icon="Plus"
          @click="showAssignDialog = true"
        >
          分配权限
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form
        :model="searchForm"
        inline
        class="search-form__content"
      >
        <el-form-item label="用户">
          <el-select
            v-model="searchForm.userId"
            placeholder="选择用户"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.displayName || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select
            v-model="searchForm.productId"
            placeholder="选择产品"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.productName"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限级别">
          <el-select
            v-model="searchForm.permissionLevel"
            placeholder="选择权限级别"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="level in permissionLevels.filter(l => l != null)"
              :key="level.level"
              :label="level.displayName"
              :value="level.level"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 权限统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-card__icon bg-purple">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ permissionStats.ownerCount }}</div>
          <div class="stat-card__title">产品负责人</div>
          <div class="stat-card__desc">拥有完全控制权限</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-card__icon bg-green">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ permissionStats.collaboratorCount }}</div>
          <div class="stat-card__title">产品协作员</div>
          <div class="stat-card__desc">拥有读写权限</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-card__icon bg-blue">
          <el-icon><View /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ permissionStats.reporterCount }}</div>
          <div class="stat-card__title">产品报告员</div>
          <div class="stat-card__desc">拥有只读权限</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-card__icon bg-orange">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ permissionStats.totalCount }}</div>
          <div class="stat-card__title">权限总数</div>
          <div class="stat-card__desc">所有权限记录</div>
        </div>
      </div>
    </div>

    <!-- 权限列表 -->
    <div class="data-table">
      <BaseTable
        :data="permissionList"
        :loading="loading"
        :stripe="true"
        :border="true"
        :pagination="true"
        :total="pagination.total"
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <el-table-column prop="userDisplayName" label="用户" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-name">{{ row.userDisplayName || row.username }}</div>
              <div class="user-username">@{{ row.username }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品" width="200">
          <template #default="{ row }">
            <div class="product-info">
              <div class="product-name">{{ row.productName }}</div>
              <div class="product-code">{{ row.productCode }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="permissionLevel" label="权限级别" width="150">
          <template #default="{ row }">
            <el-tag
              :type="getPermissionLevelTag(row.permissionLevel)"
              effect="plain"
            >
              {{ row.permissionLevelDisplayName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignedByDisplayName" label="分配人" width="150">
          <template #default="{ row }">
            <span v-if="row.assignedByDisplayName">
              {{ row.assignedByDisplayName }}
            </span>
            <span v-else class="text-muted">系统自动</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="分配时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEditPermission(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleRevokePermission(row)"
            >
              回收
            </el-button>
          </template>
        </el-table-column>
      </BaseTable>
    </div>

    <!-- 分配权限对话框 -->
    <BaseDialog
      v-model="showAssignDialog"
      title="分配产品权限"
      width="500px"
      @close="resetAssignForm"
    >
      <BaseForm
        ref="assignFormRef"
        v-model="assignForm"
        :rules="assignFormRules"
        label-width="80px"
        :show-actions="false"
        @submit="handleAssignPermission"
      >
        <el-form-item label="用户" prop="userId">
          <el-select
            v-model="assignForm.userId"
            placeholder="选择用户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.displayName || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="assignForm.productId"
            placeholder="选择产品"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.productName"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限级别" prop="permissionLevel">
          <el-select
            v-model="assignForm.permissionLevel"
            placeholder="选择权限级别"
            style="width: 100%"
          >
            <el-option
              v-for="level in permissionLevels.filter(l => l != null)"
              :key="level.level"
              :label="`${level.displayName} - ${level.description}`"
              :value="level.level"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="assignForm.remark"
            type="textarea"
            placeholder="请输入备注说明"
            :rows="3"
          />
        </el-form-item>
        <template #actions>
          <div class="dialog-footer">
            <el-button @click="showAssignDialog = false">取消</el-button>
            <el-button type="primary" @click="handleAssignPermission">确定</el-button>
          </div>
        </template>
      </BaseForm>
    </BaseDialog>

    <!-- 编辑权限对话框 -->
    <BaseDialog
      v-model="showEditDialog"
      title="编辑产品权限"
      width="500px"
      @close="resetEditForm"
    >
      <BaseForm
        ref="editFormRef"
        v-model="editForm"
        :rules="editFormRules"
        label-width="80px"
        :show-actions="false"
        @submit="handleUpdatePermission"
      >
        <el-form-item label="权限级别" prop="permissionLevel">
          <el-select
            v-model="editForm.permissionLevel"
            placeholder="选择权限级别"
            style="width: 100%"
          >
            <el-option
              v-for="level in permissionLevels.filter(l => l != null)"
              :key="level.level"
              :label="`${level.displayName} - ${level.description}`"
              :value="level.level"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            placeholder="请输入备注说明"
            :rows="3"
          />
        </el-form-item>
        <template #actions>
          <div class="dialog-footer">
            <el-button @click="showEditDialog = false">取消</el-button>
            <el-button type="primary" @click="handleUpdatePermission">确定</el-button>
          </div>
        </template>
      </BaseForm>
    </BaseDialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessageBox} from 'element-plus'
import {MessageService} from '@/utils/message'
import {DataAnalysis, Plus, Refresh, Search, User, UserFilled, View} from '@element-plus/icons-vue'
import {formatDateTime} from '@/utils/date'
import * as permissionService from '@/services/permissionService'
import * as userService from '@/services/userService'
import productService from '@/services/productService'
import BaseTable from '@/components/common/tables/BaseTable.vue'
import BaseDialog from '@/components/common/dialogs/BaseDialog.vue'
import BaseForm from '@/components/common/forms/BaseForm.vue'

// 类型定义
interface Permission {
  id: number
  userId: number
  username: string
  userDisplayName: string
  productId: number
  productCode: string
  productName: string
  permissionLevel: number
  permissionLevelDisplayName: string
  permissionLevelDescription: string
  assignedById?: number
  assignedByUsername?: string
  assignedByDisplayName?: string
  remark?: string
  createTime: string
  updateTime: string
}

interface User {
  id: number
  username: string
  displayName?: string
}

interface Product {
  id?: number
  productCode: string
  productName: string
}

interface PermissionLevel {
  level: number
  code: string
  displayName: string
  description: string
}

// 响应式数据
const loading = ref(false)
const permissionList = ref<Permission[]>([])
const userList = ref<User[]>([])
const productList = ref<Product[]>([])
const permissionLevels = ref<PermissionLevel[]>([])
const showAssignDialog = ref(false)
const showEditDialog = ref(false)

// 搜索表单
const searchForm = reactive({
  userId: null as number | null,
  productId: null as number | null,
  permissionLevel: null as number | null
})

// 分页
const pagination = reactive({
  page: 0,
  size: 20,
  total: 0
})

// 权限统计
const permissionStats = reactive({
  ownerCount: 0,
  collaboratorCount: 0,
  reporterCount: 0,
  totalCount: 0
})

// 分配权限表单
const assignFormRef = ref<FormInstance>()
const assignForm = reactive({
  userId: null as number | null,
  productId: null as number | null,
  permissionLevel: null as number | null,
  remark: ''
})

const assignFormRules: FormRules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  permissionLevel: [{ required: true, message: '请选择权限级别', trigger: 'change' }]
}

// 编辑权限表单
const editFormRef = ref<FormInstance>()
const editForm = reactive({
  id: 0,
  permissionLevel: null as number | null,
  remark: ''
})

const editFormRules: FormRules = {
  permissionLevel: [{ required: true, message: '请选择权限级别', trigger: 'change' }]
}

// 当前编辑的权限
const currentPermission = ref<Permission | null>(null)

// 方法
const loadPermissions = async () => {
  try {
    loading.value = true
    const response = await permissionService.searchPermissions({
      userId: searchForm.userId || undefined,
      productId: searchForm.productId || undefined,
      permissionLevel: searchForm.permissionLevel || undefined,
      page: pagination.page,
      size: pagination.size
    })

    // 检查API响应格式
    console.log('权限API响应:', response)

    // 根据新的API响应格式，从response.data获取PageResponse数据
    if (response.success && response.data) {
      const pageData = response.data
      permissionList.value = pageData.content || []
      pagination.total = pageData.totalElements || 0
    } else {
      permissionList.value = []
      pagination.total = 0
      MessageService.error(response.error?.message || '加载权限列表失败')
    }
    console.log('权限列表数据:', permissionList.value)

    // 加载完权限列表后，更新统计信息
    loadPermissionStats()
  } catch (error) {
    console.error('加载权限列表失败:', error)
    MessageService.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const loadUsers = async () => {
  try {
    const response = await userService.getUsers()
    // 根据新的API响应格式，从response.data获取用户数组
    const users = (response.success && response.data) ? response.data : []
    userList.value = users
  } catch (error) {
    console.error('加载用户列表失败:', error)
    userList.value = [] // 出错时设置为空数组
  }
}

const loadProducts = async () => {
  try {
    const response = await productService.getAllProducts()
    if (response.success) {
      productList.value = response.data?.filter((p: any) => p.id) || []
    } else {
      console.error('加载产品列表失败:', response.error?.message)
      productList.value = []
    }
  } catch (error) {
    console.error('加载产品列表失败:', error)
    productList.value = [] // 出错时设置为空数组
  }
}

const loadPermissionLevels = async () => {
  try {
    const response = await permissionService.getPermissionLevels()
    // 根据新的API响应格式，从response.data获取权限级别数组
    const levels = (response.success && response.data) ? response.data : []
    permissionLevels.value = levels.filter((level: any) => level != null && level.level != null)
  } catch (error) {
    console.error('加载权限级别失败:', error)
    permissionLevels.value = [] // 出错时设置为空数组
  }
}

const loadPermissionStats = async () => {
  try {
    let stats
    if (searchForm.productId) {
      // 如果选择了产品，获取该产品的权限统计
      const response = await permissionService.getPermissionStats(searchForm.productId)
      // 根据新的API响应格式，从response.data获取统计数据
      stats = (response.success && response.data) ? response.data : calculateStatsFromPermissions()
    } else {
      // 如果没有选择产品，从当前权限列表计算统计信息
      stats = calculateStatsFromPermissions()
    }

    // 更新统计数据
    Object.assign(permissionStats, stats)
    console.log('权限统计数据:', stats)
  } catch (error) {
    console.error('加载权限统计失败:', error)
    // 出错时重置为0
    Object.assign(permissionStats, {
      ownerCount: 0,
      collaboratorCount: 0,
      reporterCount: 0,
      totalCount: 0
    })
  }
}

// 从权限列表计算统计信息
const calculateStatsFromPermissions = () => {
  const stats = {
    ownerCount: 0,
    collaboratorCount: 0,
    reporterCount: 0,
    totalCount: permissionList.value.length
  }

  permissionList.value.forEach(permission => {
    switch (permission.permissionLevel) {
      case 1:
        stats.ownerCount++
        break
      case 2:
        stats.collaboratorCount++
        break
      case 3:
        stats.reporterCount++
        break
    }
  })

  return stats
}

const handleSearch = () => {
  pagination.page = 0
  loadPermissions()
}

const handleReset = () => {
  searchForm.userId = null
  searchForm.productId = null
  searchForm.permissionLevel = null
  pagination.page = 0
  Object.assign(permissionStats, {
    ownerCount: 0,
    collaboratorCount: 0,
    reporterCount: 0,
    totalCount: 0
  })
  loadPermissions()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 0
  loadPermissions()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadPermissions()
}

const handleAssignPermission = async () => {
  if (!assignFormRef.value) return

  try {
    await assignFormRef.value.validate()
    // 确保所有字段都有值
    const requestData = {
      userId: assignForm.userId!,
      productId: assignForm.productId!,
      permissionLevel: assignForm.permissionLevel!,
      remark: assignForm.remark
    }
    await permissionService.assignPermission(requestData)
    MessageService.success('权限分配成功')
    showAssignDialog.value = false
    resetAssignForm()
    loadPermissions()
    loadPermissionStats()
  } catch (error) {
    console.error('分配权限失败:', error)
  }
}

const handleEditPermission = (permission: Permission) => {
  currentPermission.value = permission
  editForm.id = permission.id
  editForm.permissionLevel = permission.permissionLevel
  editForm.remark = permission.remark || ''
  showEditDialog.value = true
}

const handleUpdatePermission = async () => {
  if (!editFormRef.value || !currentPermission.value) return

  try {
    await editFormRef.value.validate()
    // 确保所有字段都有值
    const requestData = {
      permissionLevel: editForm.permissionLevel!,
      remark: editForm.remark
    }
    await permissionService.updatePermission(
      currentPermission.value.userId,
      currentPermission.value.productId,
      requestData
    )
    showEditDialog.value = false
    resetEditForm()
    loadPermissions()
    loadPermissionStats()
  } catch (error) {
    console.error('更新权限失败:', error)
  }
}

const handleRevokePermission = async (permission: Permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要回收用户 ${permission.userDisplayName} 在产品 ${permission.productName} 的权限吗？`,
      '确认回收',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await permissionService.revokePermission(permission.userId, permission.productId)
    MessageService.success('权限回收成功')
    loadPermissions()
    loadPermissionStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回收权限失败:', error)
    }
  }
}

const resetAssignForm = () => {
  assignForm.userId = null
  assignForm.productId = null
  assignForm.permissionLevel = null
  assignForm.remark = ''
  assignFormRef.value?.resetFields()
}

const resetEditForm = () => {
  editForm.id = 0
  editForm.permissionLevel = null
  editForm.remark = ''
  currentPermission.value = null
  editFormRef.value?.resetFields()
}

const getPermissionLevelTag = (level: number) => {
  switch (level) {
    case 1:
      return 'danger'
    case 2:
      return 'success'
    case 3:
      return 'info'
    default:
      return ''
  }
}

// 生命周期
onMounted(() => {
  loadPermissions()
  loadUsers()
  loadProducts()
  loadPermissionLevels()
})
</script>

<style scoped>
/* 产品权限管理页面特有样式 */

/* 对话框底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--dbu-space-3);
}

/* 确保BaseForm中的actions插槽样式正确 */
:deep(.base-form .dialog-footer) {
  margin-top: var(--dbu-space-6);
  padding-top: var(--dbu-space-4);
  border-top: 1px solid var(--el-border-color-light);
}
</style>